package com.loadmore.oneday.fragment

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.loadmore.common.base.BaseAdapter
import com.loadmore.common.base.BaseFragment
import com.loadmore.common.constants.Api
import com.loadmore.common.model.BaseResponse
import com.loadmore.common.model.Category
import com.loadmore.common.model.Topic
import com.loadmore.common.net.Request
import com.loadmore.common.net.impl.JsonCallback
import com.loadmore.common.router.RouterPath
import com.loadmore.oneday.R
import com.loadmore.oneday.adapter.TopicListAdapter
import com.lzy.okgo.model.Response

/**
 *@author sunleilei
 *@date 2018/7/18
 *@time 16:12
 *
 */

@Route(path = RouterPath.TopicList)
class TopicListFragment:BaseFragment() {

   lateinit  var adapter:BaseAdapter
    override fun getLayoutId(): Int {
        return R.layout.fragment_base_list
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setNavigationIcon(true)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setRefreshEnable(true)
//        setLoadEnable(true)
        adapter = TopicListAdapter(context!!)
        var base_list:androidx.recyclerview.widget.RecyclerView = view.findViewById(R.id.base_list)
        base_list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        base_list.adapter = adapter
        val data:Category = arguments?.getSerializable("data") as Category
        actionBarTitle(data.getName())
        getTopics(data.getId().toString(),false)
        refreshLayout.setOnRefreshListener {
            getTopics(data.getId().toString(),true)
        }

    }

    private fun getTopics(id:String,refresh: Boolean) {

        showLoading()
        Request.get(Api.topics, hashMapOf<String,Any>("category_id" to id), object :JsonCallback<BaseResponse<List<Topic>>>(){
            override fun onSuccess(response: Response<BaseResponse<List<Topic>>>?) {
                if (refresh)
                    adapter.clear()
                var data = response?.body()?.data
                if (data != null && data.isNotEmpty()) {
                    adapter.append(data)
                    showContent()
                }else{
                    showEmpty()
                }


            }

            override fun onError(response: Response<BaseResponse<List<Topic>>>?) {
                super.onError(response)
            }

        })
    }
}